package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServcieImpl implements ApBehaviorServcie {

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 查询文章行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.参数校验
        if (dto.getArticleId() == null || dto.getAuthorId()==null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录用户id
        ApUser apUser = ApThreadLocal.getApUser();
        //表示未登录
        if(apUser==null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if(apUser.getId()==0){
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }

        Boolean isfollow=false,iscollection=false,isunlike=false,islike=false;


        //3.查看是否关注该用户
        String follow_key="USER_FOLLOW_"+apUser.getId();
        Boolean followFlag = redisTemplate.opsForHash().hasKey(follow_key, dto.getAuthorId() + "");
        if(followFlag){
           isfollow=true;
        }

        //4.查询是否点赞了该文章
        String likes_key="USER_LIKES_"+dto.getArticleId();
        Boolean likesFlag = redisTemplate.opsForHash().hasKey(likes_key, apUser.getId() + "");
        if(likesFlag){
            islike=true;
        }
        //5.查询是否不喜欢该文章
        String unlikes_key="USER_UNLIKES_"+dto.getArticleId();
        Boolean unlikesFlag = redisTemplate.opsForHash().hasKey(unlikes_key, apUser.getId() + "");
        if(unlikesFlag){
            isunlike=true;
        }

        //6.查看是否收藏了该文章
        String collection_key="USER_COLLECTION_"+dto.getArticleId();
        Boolean collectionFlag = redisTemplate.opsForHash().hasKey(collection_key, apUser.getId() + "");
        if(collectionFlag){
            iscollection=true;
        }

        //7.返回数据
        Map map=new HashMap();
        map.put("isfollow",isfollow);
        map.put("iscollection",iscollection);
        map.put("isunlike",isunlike);
        map.put("islike",islike);

        return ResponseResult.okResult(map);
    }
}
